package com.difsonapps.android.marker.activities;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.difsonapps.android.marker.R;
import com.difsonapps.android.marker.R.layout;
import com.difsonapps.android.marker.R.menu;
import com.difsonapps.android.marker.services.InviteFacebookFriendsIntentService;
import com.facebook.HttpMethod;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.Session.StatusCallback;
import com.sromku.simple.fb.Permission;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.entities.Profile;
import com.sromku.simple.fb.listeners.OnAlbumsListener;
import com.sromku.simple.fb.listeners.OnFriendsListener;
import com.sromku.simple.fb.listeners.OnInviteListener;
import com.sromku.simple.fb.listeners.OnLoginListener;
import com.sromku.simple.fb.listeners.OnNewPermissionsListener;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class TestActivity extends Activity {
    static final String PENDING_REQUEST_BUNDLE_KEY = "com.difsonapps.android.marker:PendingRequest";
    Session session;
    boolean pendingRequest;
	SimpleFacebook mSimpleFacebook;
	public static final String TAG = "TestActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_test);
        this.session = createSession();
        Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.test, menu);
		return true;
	}

	public void btnRequestOnClick(View view){
		toast("Opened : "+session.isOpened());
		
		
		
		
		Bundle params = new Bundle();

		params.putString("href", "/testurl?param1=value1");
		params.putString("template", "This is a test message");
		/* make the API call */
		new Request(
		    session,
		    "/me/notifications",
		    params,
		    HttpMethod.POST,
		    new Request.Callback() {
		        public void onCompleted(Response response) {
		        	Log.d("Request", response.toString());
		        }
		    }
		).executeAsync();
		if(true) return;
		
		
		params.putString("message", "This is a test message");
		//params.putString("ids", "1377777285846195");
		params.putString("ids", "10204644877620022");
		/* make the API call */
		
		 new Request(
		    session,
		    "/me/apprequests",
		    params,
		    HttpMethod.POST,
		    new Request.Callback() {
				
				@Override
				public void onCompleted(Response response) {
					Log.d("Request", response.toString());
					// TODO Auto-generated method stub
					
				}
			}
		).executeAsync();
		 
	}
	public void btnLogoutOnClick(View view){
		toast("Login ...");
		pendingRequest = true;
		if(this.session.isOpened()) {
			this.session.closeAndClearTokenInformation();
			this.session = createSession();
		}
        
		//mSimpleFacebook.login(onLoginListener);
	}
	
	public void btnLoginOnClick(View view){
		toast("Login ...");
		pendingRequest = true;
        if(!this.session.isOpened()) {
        	//this.session.openForRead(new Session.OpenRequest(this).setCallback(callback));
        	this.session = Session.openActiveSession(TestActivity.this, true, callback);
        }else{
        	if(this.session.getPermissions().isEmpty()){
        		this.session.requestNewReadPermissions(new Session.NewPermissionsRequest(this, "user_friends", "email", "user_photos"));
        	}
        }
        
		//mSimpleFacebook.login(onLoginListener);
	}	
	
	StatusCallback callback = new StatusCallback() {
        public void call(Session session, SessionState state, Exception exception) {
            if (exception != null) {
                new AlertDialog.Builder(TestActivity.this)
                        .setTitle(R.string.an_error_occured)
                        .setMessage(exception.getMessage())
                        .setPositiveButton(R.string.ok_button, null)
                        .show();
                TestActivity.this.session = createSession();
            }
        }
    };
	
	public void btnIsLoginOnClick(View view){
		if(this.session==null) toast("Null");
		else if(!session.isOpened()) toast("Not opened");
		else toast("Session opened");
		if(session.isOpened()) Log.d("Permissions : ", session.getPermissions().toString());
		/*if(mSimpleFacebook.isLogin()) toast("Logged  in ...");
		else toast("Not logged in");*/
	}	
	
	public void btnImportAlbumsOnClick(View view){
		//String myId = "1177766306";
		String myId = "me";
		toast("Loading my albums ...");
		mSimpleFacebook.getAlbums(myId, onAlbumsListener);
	}	
	
	public void btnGetFriendsOnClick(View view){
		new Request(
			    session,
			    "/me/friends",
			    null,
			    HttpMethod.GET,
			    new Request.Callback() {
					
					@Override
					public void onCompleted(Response response) {
						Log.d("Request friends", response.toString());
						// TODO Auto-generated method stub
						
					}
				}
			).executeAsync();
		if(true) return;
		/*List<String> permissions = mSimpleFacebook.getGrantedPermissions();
		Log.d("Granted permissions", permissions.toString());
		if(!permissions.contains("user_friends")){
			Permission[] permissions2 = new Permission[] { 
				    Permission.USER_VIDEOS
				};
			boolean showPublish = false;
			mSimpleFacebook.requestNewPermissions(permissions2, showPublish, onNewPermissionsListener);
			return;
		}
		mSimpleFacebook.getFriends(onFriendsListener);*/
		mSimpleFacebook.invite(/*new String[]{"1177766306", "1602632647"},*/ "I invite you to use this app", onInviteListener, null);
		
	    /*ArrayList<String> friendsIds = new ArrayList<String>();
	    friendsIds.add("1177766306");//ID me
	    friendsIds.add("1602632647");//ID difson
	    InviteFacebookFriendsIntentService.startActionInviteFriend(this, friendsIds);
	    toast("Service started");*/
	}
	OnInviteListener onInviteListener = new OnInviteListener() {
	    @Override
	    public void onComplete(List<String> invitedFriends, String requestId) {
	    	/*Intent intent = new Intent(NOTIFICATION);
		    intent.putExtra(NB_INVITATIONS, invitedFriends.size());
		    intent.putExtra(RESULT, Activity.RESULT_OK);
		    sendBroadcast(intent);
		    Log.d(this.getClass().getCanonicalName(), "Broadcast sent");
		    */
	        Log.i(this.getClass().getCanonicalName(), "Invited friend " + invitedFriends.toString() + " ; users with request id " + requestId); 
	    }

	    @Override
	    public void onCancel() {
	        Log.i(this.getClass().getCanonicalName(), "Canceled the dialog");
	    }

		@Override
		public void onException(Throwable throwable) {
			Log.e(this.getClass().getCanonicalName(), throwable.getMessage());
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onFail(String reason) {
			Log.w(this.getClass().getCanonicalName(), reason);
			// TODO Auto-generated method stub
			
		}

	    /* 
	     * You can override other methods here: 
	     * onFail(String reason), onException(Throwable throwable)
	     */
	};
	
	
	
	
	@Override
	public void onResume() {
	    super.onResume();
	    mSimpleFacebook = SimpleFacebook.getInstance(this);
	    registerReceiver(receiver, new IntentFilter(InviteFacebookFriendsIntentService.NOTIFICATION));
	}
	
	@Override
	protected void onPause() {
	    super.onPause();
	    unregisterReceiver(receiver);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (this.session.onActivityResult(this, requestCode, resultCode, data) &&
                pendingRequest &&
                this.session.getState().isOpened()) {
            sendRequests();
        } 
	    mSimpleFacebook.onActivityResult(this, requestCode, resultCode, data); 
	    super.onActivityResult(requestCode, resultCode, data);
	}
	
	@Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        pendingRequest = savedInstanceState.getBoolean(PENDING_REQUEST_BUNDLE_KEY, pendingRequest);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putBoolean(PENDING_REQUEST_BUNDLE_KEY, pendingRequest);
    }
	
	OnLoginListener onLoginListener = new OnLoginListener() {
	    @Override
	    public void onLogin() {
	        // change the state of the button or do whatever you want
	        Log.i(TAG, "Logged in");
	    }

	    @Override
	    public void onNotAcceptingPermissions(Permission.Type type) {
	        // user didn't accept READ or WRITE permission
	        Log.w(TAG, String.format("You didn't accept %s permissions", type.name()));
	    }

		@Override
		public void onThinking() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onException(Throwable throwable) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onFail(String reason) {
			// TODO Auto-generated method stub
			
		}

	    /* 
	     * You can override other methods here: 
	     * onThinking(), onFail(String reason), onException(Throwable throwable)
	     */ 
	};
	
	OnAlbumsListener onAlbumsListener = new OnAlbumsListener() {            
	    @Override
	    public void onComplete(List<com.sromku.simple.fb.entities.Album> albums) {
	        Log.i(TAG, "Number of albums = " + albums.size());
	    }

	    /* 
	     * You can override other methods here: 
	     * onThinking(), onFail(String reason), onException(Throwable throwable)
	     */     
	};
	
	OnFriendsListener onFriendsListener = new OnFriendsListener() {         
	    @Override
	    public void onComplete(List<Profile> friends) {
	        Log.i(TAG, "Number of friends = " + friends.size());
	    }

	    /* 
	     * You can override other methods here: 
	     * onThinking(), onFail(String reason), onException(Throwable throwable)
	     */         
	};
	
	OnNewPermissionsListener onNewPermissionsListener = new OnNewPermissionsListener() {

	    @Override
	    public void onSuccess(String accessToken) {
	    	mSimpleFacebook.getFriends(onFriendsListener);
	    }

	    @Override
	    public void onNotAcceptingPermissions(Permission.Type type) {
	        // user didn't accept READ or WRITE permission
	        Log.w(TAG, String.format("You didn't accept %s permissions", type.name()));
	    }

		@Override
		public void onThinking() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onException(Throwable throwable) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onFail(String reason) {
			// TODO Auto-generated method stub
			
		}

	};
	
	private BroadcastReceiver receiver = new BroadcastReceiver() {

	    @Override
	    public void onReceive(Context context, Intent intent) {
	      Bundle bundle = intent.getExtras();
	      if (bundle != null) {
	        int nbInvitationsSent = bundle.getInt(InviteFacebookFriendsIntentService.NB_INVITATIONS);
	        int resultCode = bundle.getInt(InviteFacebookFriendsIntentService.RESULT);
	        if (resultCode == RESULT_OK) {
	        	toast(""+nbInvitationsSent+" invitation(s) sent");
	        } else {
	          toast("Invitation failed");
	        }
	      }
	    }
	  };
	
	  
	  private Session createSession() {
	        Session activeSession = Session.getActiveSession();
	        if (activeSession == null || activeSession.getState().isClosed()) {
	            activeSession = new Session.Builder(this).setApplicationId(getResources().getString(R.string.app_id)).build();
	            Session.setActiveSession(activeSession);
	        }
	        return activeSession;
	    }
	  
	  private void sendRequests() {
		  
	  }

	public void toast(String text){
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}

}
